# -*- coding: utf-8 -*-
# @Time : 2022/10/25 23:30
# @Author : renyumeng
# @Email : 2035328756@qq.com
# @File : MyCNN.py
# @Project : pythonFile
from utils import *


class MyNet(nn.Module):
    def __init__(self):
        super(MyNet, self).__init__()
        self.con1 = nn.Sequential(
            nn.Conv1d(in_channels=1, out_channels=32, kernel_size=4, stride=4, padding=0),
            nn.BatchNorm1d(32),
            nn.ReLU(),
        )
        self.con2 = nn.Sequential(
            nn.Conv1d(in_channels=32, out_channels=64, kernel_size=5, stride=5, padding=0),
            nn.BatchNorm1d(64),
            nn.ReLU(),
        )
        self.con3 = nn.Sequential(
            nn.Conv1d(in_channels=64, out_channels=128, kernel_size=5, stride=5, padding=0),
            nn.BatchNorm1d(128),
            nn.ReLU(),
        )
        self.con4 = nn.Sequential(
            nn.Conv1d(in_channels=128, out_channels=256, kernel_size=5, stride=5, padding=0),
            nn.BatchNorm1d(256),
            nn.ReLU(),
        )
        self.con5 = nn.Sequential(
            nn.Conv1d(in_channels=256, out_channels=512, kernel_size=5, stride=5, padding=0),
            nn.BatchNorm1d(512),
            # nn.MaxPool1d(kernel_size=1),
            nn.ReLU(),
        )

        self.fc = nn.Sequential(
            # 线性分类器
            nn.Linear(16 * 512, 1024),  # 修改大小后要重新计算
            nn.ReLU(),
            nn.Linear(1024, 512),
            nn.ReLU(),
            nn.Linear(512, 1),
            # nn.Softmax(dim=1),
        )
        self.mls = nn.MSELoss()
        self.opt = torch.optim.Adam(params=self.parameters(), lr=1e-3)
        # self.start = datetime.datetime.now()

    def forward(self, inputs):
        out = self.con1(inputs)
        out = self.con2(out)
        out = self.con3(out)
        out = self.con4(out)
        out = self.con5(out)
        # print(out)
        # print(len(out))
        out = out.reshape(-1, 512 * 16)
        out = self.fc(out)
        return out

    def train1(self, x, y, txt, zhunquelv):
        out = self.forward(x)
        # print("dcgfhjkvscghjkjvfdhmjewkffvhjewk")
        self.opt.zero_grad()
        loss = self.mls(out, y)
        print('loss: ', loss * 10)
        # print(len(out))
        for i in range(len(out)):
            j = abs(out[i].item() - y[i].item()) / y[i].item()
            zhunquelv.append(j)
        txt.append(loss.item())
        loss.backward()
        self.opt.step()

    def test(self, x):
        out = self.forward(x)
        # loss = self.mls(out, y)
        return out

    def get_data(self, path_csv, path_lable):
        result = []
        lables = []
        for filename in tqdm(os.listdir(path_csv)):
            # print(filename)
            results = []
            labless = []
            paths_csv = path_csv + "/" + filename
            paths_lable = path_lable + "/" + filename[:-4] + ".txt"
            df = pd.read_csv(paths_csv)
            lable = pd.read_table(paths_lable, sep=',', header=None)
            lable = lable[0][0]
            S = list(df['zs_201_bpi'])
            S1 = list(df['zs_202_pi'])
            S2 = list(df['zs_201_zuv'])
            S3 = list(df['zs_201_ocw'])
            S4 = list(df['zs_201_scms'])
            results.append(S[0:10000])
            results.append(S1[0:10000])
            results.append(S2[0:10000])
            results.append(S3[0:10000])
            results.append(S4[0:10000])
            inputs = np.array(results)
            l = len(inputs[0])
            inputs = inputs.T
            # inputs = torch.from_numpy(inputs).float()
            inputs = inputs.reshape(1, 5 * l)
            result.append(inputs)

            lable = [lable]
            labless = np.array(lable)
            # lable = torch.from_numpy(lable).float()
            lables.append(labless)
        result = np.array(result)
        results = torch.from_numpy(result).float()
        lables = np.array(lables)
        lablesss = torch.from_numpy(lables).float()

        return results, lablesss

    def get_test_data(self, path):
        df = pd.read_csv(path)
        results = []
        S = list(df['zs_201_bpi'])
        S1 = list(df['zs_202_pi'])
        S2 = list(df['zs_201_zuv'])
        S3 = list(df['zs_201_ocw'])
        S4 = list(df['zs_201_scms'])

        num_0 = 0
        num_n = 0
        for j in range(len(S)):
            num_n += 1
            if j >= 1 and S[j] <= 0:
                num = S[j - 1]
                S[j] = num
            if j >= 1 and abs(S[j] - S[j - 1]) >= 1:
                num_m = S[j]
                S[j] = S[j - 1]
                num_0 += 1
            if num_0 >= 4:
                S[j - 1], S[j] = num_m, num_m
                num_0 = 0
            if num_n >= 4:
                num_0 = 0
                num_n = 0

        num_0 = 0
        num_n = 0
        for k in range(len(S1)):
            num_n += 1
            if k >= 1 and S1[k] <= 0:
                num = S1[k - 1]
                S1[k] = num
            if k >= 1 and abs(S1[k] - S1[k - 1]) >= 1:
                num_m = S1[k]
                S1[k] = S1[k - 1]
                num_0 += 1
            if num_0 >= 4:
                S1[k - 1], S1[k] = num_m, num_m
                num_0 = 0
            if num_n >= 4:
                num_0 = 0
                num_n = 0

        results.append(S[0:10000])
        results.append(S1[0:10000])
        results.append(S2[0:10000])
        results.append(S3[0:10000])
        results.append(S4[0:10000])
        inputs = np.array(results)
        l = len(inputs[0])
        inputs = inputs.T
        inputs = inputs.reshape(1, 5 * l)
        result = [inputs]
        result = np.array(result)
        inputs = torch.from_numpy(result).float()

        return inputs
